package com.meirengu.webview.service.impl;

import com.meirengu.channel.service.WithMeService;
import com.meirengu.common.RedisClient;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.DateUtils;
import com.meirengu.utils.NumberUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.common.UserChannelEnum;
import com.meirengu.webview.dao.KwInterfaceConfigDao;
import com.meirengu.webview.model.KwInterfaceConfig;
import com.meirengu.webview.model.KwXxjrFilter;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.KwXxjrFilterService;
import com.meirengu.webview.service.KwXxjrPushService;
import com.meirengu.webview.service.UserInfoService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * KwXxjrFilter服务实现层
 *
 * @author Mao
 * @create Tue May 08 11:10:42 CST 2018
 */
@Service
public class KwXxjrFilterServiceImpl extends BaseServiceImpl<KwXxjrFilter> implements KwXxjrFilterService {


    @Autowired
    private RedisClient redisClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private KwInterfaceConfigDao kwInterfaceConfigDao;

    @Autowired
    private WithMeService withMeService;

    @Autowired
    private KwXxjrPushService kwXxjrPushService;


    Logger logger = LoggerFactory.getLogger(KwXxjrFilterServiceImpl.class);


    /**
     * 发送贷上我接口
     * 过滤条件
     * 1.地区
     * 2.金额
     * 3.3其一
     *
     * @param userInfo
     * @param user
     */
    public boolean sendWithMe(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        try {
            String xxjrIol = redisClient.get("iol-xxjr");
            if ("N".equals(xxjrIol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                Integer creditSituation = userInfo.getCredit();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer lifeInsurance = userInfo.getPolicy();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer profession = userInfo.getOccupation();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer housingFund = userInfo.getFund();
                Integer income = userInfo.getSalary();
                Integer paytype = userInfo.getSalaryMethod();
                String ip = userInfo.getIp();
                Integer wxloan = userInfo.getWxloan();
                int age = 25;
                age = DateUtils.getAge(brithdayDate);

                KwXxjrFilter kwXxjrFilter = new KwXxjrFilter();
                kwXxjrFilter.setUserId(id);
                kwXxjrFilter.setMobile(mobile);
                kwXxjrFilter.setChannelCode("xxjr");
                kwXxjrFilter.setChannelName("贷上我");


                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("xxjr");


                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwXxjrFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwXxjrFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwXxjrFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "")) {

                            String sexStr = (sex == 0 ? "1" : "0");
                            String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                            int loanAmount = (expectAmount.divide(new BigDecimal(10000))).intValue();
                            if (loanAmount < 1) {
                                loanAmount = 1;
                            }
                            //默认上班族
                            String workType = "4";
                            //职业  0白领   1私企业主  2公务员
                            if (profession.intValue() == 1) {
                                //企业主
                                workType = "2";
                            }
                            String socialType = "1";
                            //社保   0无社保   1一年以内    2一年以上
                            if (socialSecurity.intValue() == 0) {
                                socialType = "2";
                            }
                            String fundType = "1";
                            //住房公积金   0无公积金   1一年以内    2一年以上
                            if (housingFund.intValue() == 0) {
                                fundType = "2";
                            }
                            String houseType = "1";
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (housingType.intValue() == 1) {
                                houseType = "2";
                            }
                            String carType = "1";
                            //名下车   1 无车   2 有车贷    3有车无贷
                            if (hasCar.intValue() == 1) {
                                //无车，准备买车
                                carType = "5";
                            } else if (hasCar.intValue() == 2) {
                                //贷款车
                                carType = "3";
                            } else if (hasCar.intValue() == 3) {
                                //全款车
                                carType = "4";
                            }
                            String creditType = "1";
                            //信用情况 1无信用卡无贷款   2有信用卡或贷款
                            if (creditSituation.intValue() == 1) {
                                creditType = "2";
                            }
                            //默认：1w
                            String incomeStr = "20000";
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            if (income.intValue() == 1) {
                                incomeStr = "3000";
                            } else if (income.intValue() == 2) {
                                incomeStr = "5000";
                            } else if (income.intValue() == 3) {
                                incomeStr = "8000";
                            } else if (income.intValue() == 4) {
                                incomeStr = "10000";
                            }
                            //工资发放方式  1 银行转账  2 现金发放
                            String wagesType = paytype + "";
                            String insurType = "1";
                            //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
                            if (lifeInsurance.intValue() == 1) {
                                insurType = "0";
                            }
                            String haveWeiLi = "5000";
                            if (wxloan.intValue() == 2) {
                                haveWeiLi = "0";
                            }
                            Integer code = withMeService.applyLoan(mobile, name, sexStr, birthdayStr, loanAmount + "",
                                    city + "市", workType, socialType, fundType, houseType, carType, creditType,
                                    incomeStr, wagesType, insurType, ip, age + "", haveWeiLi);
                            kwXxjrFilter.setSuited("Y");
                            kwXxjrFilter.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "xxjr", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            kwXxjrFilter.setRefuseMsg("无保单：" + lifeInsurance.intValue() + " 无房：" +
                                    housingType.intValue() + " 无车：" + hasCar.intValue());
                        }
                    }
                }

                insert(kwXxjrFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }

    /**
     * 发送贷上2渠道我接口
     * 过滤条件
     * 1.地区
     * 2.金额
     * 3.3其一
     *
     * @param userInfo
     * @param user
     */
    public boolean sendWithMe2(UserInfo userInfo, User user) throws Exception {

        boolean sendFlag = false;
        //校验是否有一财道普惠发送成功的记录
        Map<String, Object> xxjrParams = new HashMap<>();
        xxjrParams.put("mobile", user.getMobile());
        xxjrParams.put("interfaceCode", "xxjr2");
        xxjrParams.put("code", 1);
        Integer xxjrCount = kwXxjrPushService.getCount(xxjrParams);
        //已有成功发送记录
        if (!NumberUtil.isNullOrZero(xxjrCount)) {
            return sendFlag;
        }
        try {
            String xxjr2Iol = redisClient.get("iol-xxjr2");
            if ("N".equals(xxjr2Iol)) {
                Date brithdayDate = userInfo.getBirthday();
                String id = user.getId();
                String name = user.getName();
                String mobile = user.getMobile();
                Integer sex = user.getSex();
                String city = userInfo.getScity();
                Integer creditSituation = userInfo.getCredit();
                Integer housingType = userInfo.getHouse();
                Integer hasCar = userInfo.getCar();
                Integer lifeInsurance = userInfo.getPolicy();
                BigDecimal expectAmount = userInfo.getExpectAmount();
                Integer profession = userInfo.getOccupation();
                Integer socialSecurity = userInfo.getSocialSecurity();
                Integer housingFund = userInfo.getFund();
                Integer income = userInfo.getSalary();
                Integer paytype = userInfo.getSalaryMethod();
                String ip = userInfo.getIp();
                Integer wxloan = userInfo.getWxloan();
                int age = 25;
                age = DateUtils.getAge(brithdayDate);

                KwXxjrFilter kwXxjrFilter = new KwXxjrFilter();
                kwXxjrFilter.setUserId(id);
                kwXxjrFilter.setMobile(mobile);
                kwXxjrFilter.setChannelCode("xxjr2");
                kwXxjrFilter.setChannelName("贷上我2");

                KwInterfaceConfig kwInterfaceConfig = kwInterfaceConfigDao.findByCode("xxjr2");


                boolean dataFlag = true;
                if (kwInterfaceConfig != null) {
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitArea())) {
                        city = city.replace("市", "");
                        String cityRange = kwInterfaceConfig.getAreaValue();
                        if (!cityRange.contains(city)) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_AREA.getValue());
                            kwXxjrFilter.setRefuseMsg("用户所在城市不满足：" + city);
                        }
                    }
                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAge())) {
                        if (age < kwInterfaceConfig.getMinAge().intValue() || age > kwInterfaceConfig.getMaxAge().intValue()) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_AGE.getValue());
                            kwXxjrFilter.setRefuseMsg("用户年龄不符合：" + age);
                        }
                    }

                    if (dataFlag && "Y".equals(kwInterfaceConfig.getLimitAmount())) {
                        if (expectAmount.intValue() < kwInterfaceConfig.getMinAmount() || expectAmount.intValue() > kwInterfaceConfig.getMaxAmount()) {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_LOW_AMOUNT.getValue());
                            kwXxjrFilter.setRefuseMsg("申请贷款额度小于" + kwInterfaceConfig.getMinAmount() + "w：" + expectAmount);
                        }
                    }
                    if (dataFlag) {
                        if (kwInterfaceConfig.getHouseValue().contains(housingType.intValue() + "") ||
                                kwInterfaceConfig.getCarValue().contains(hasCar.intValue() + "") ||
                                kwInterfaceConfig.getPolicyValue().contains(lifeInsurance.intValue() + "") ||
                                kwInterfaceConfig.getSocialSecurityValue().contains(socialSecurity.intValue() + "") ||
                                kwInterfaceConfig.getFundValue().contains(housingFund.intValue() + "")) {

                            String sexStr = (sex == 0 ? "1" : "0");
                            String birthdayStr = DateUtils.dateToStr(brithdayDate, "yyyy-MM-dd");
                            int loanAmount = (expectAmount.divide(new BigDecimal(10000))).intValue();
                            if (loanAmount < 1) {
                                loanAmount = 1;
                            }
                            //默认上班族
                            String workType = "4";
                            //职业  0白领   1私企业主  2公务员
                            if (profession.intValue() == 1) {
                                //企业主
                                workType = "2";
                            }
                            String socialType = "1";
                            //社保   0无社保   1一年以内    2一年以上
                            if (socialSecurity.intValue() == 0) {
                                socialType = "2";
                            }
                            String fundType = "1";
                            //住房公积金   0无公积金   1一年以内    2一年以上
                            if (housingFund.intValue() == 0) {
                                fundType = "2";
                            }
                            String houseType = "1";
                            //名下房产  1 无房   2 有房贷   3有房无贷
                            if (housingType.intValue() == 1) {
                                houseType = "2";
                            }
                            String carType = "1";
                            //名下车   1 无车   2 有车贷    3有车无贷
                            if (hasCar.intValue() == 1) {
                                //无车，准备买车
                                carType = "5";
                            } else if (hasCar.intValue() == 2) {
                                //贷款车
                                carType = "3";
                            } else if (hasCar.intValue() == 3) {
                                //全款车
                                carType = "4";
                            }
                            String creditType = "1";
                            //信用情况 1无信用卡无贷款   2有信用卡或贷款
                            if (creditSituation.intValue() == 1) {
                                creditType = "2";
                            }
                            //默认：1w
                            String incomeStr = "20000";
                            //月薪   1 3000以下  2 3000-5000  3 5001-8000   4 8001-10000  5 1w以上
                            if (income.intValue() == 1) {
                                incomeStr = "3000";
                            } else if (income.intValue() == 2) {
                                incomeStr = "5000";
                            } else if (income.intValue() == 3) {
                                incomeStr = "8000";
                            } else if (income.intValue() == 4) {
                                incomeStr = "10000";
                            }
                            //工资发放方式  1 银行转账  2 现金发放
                            String wagesType = paytype + "";
                            String insurType = "1";
                            //寿险  1 无寿险   2 寿险2400以下   3 寿险2400以上
                            if (lifeInsurance.intValue() == 1) {
                                insurType = "0";
                            }
                            String haveWeiLi = "5000";
                            if (wxloan.intValue() == 2) {
                                haveWeiLi = "0";
                            }
                            Integer code = withMeService.applyLoan2(mobile, name, sexStr, birthdayStr, loanAmount + "",
                                    city + "市", workType, socialType, fundType, houseType, carType, creditType,
                                    incomeStr, wagesType, insurType, ip, age + "", haveWeiLi);
                            kwXxjrFilter.setSuited("Y");
                            kwXxjrFilter.setCode(UserChannelEnum.PASS.getValue());
                            /*推送接口后修改限制数量*/
                            userInfoService.updateLimitNum(code, "xxjr2", user);
                            if (code.intValue() == Constants.BUSINESS_STATUS_SUCCESS) {
                                sendFlag = true;
                            }
                        } else {
                            dataFlag = false;
                            kwXxjrFilter.setSuited("N");
                            kwXxjrFilter.setCode(UserChannelEnum.FAIL_O2O.getValue());
                            kwXxjrFilter.setRefuseMsg("无保单：" + lifeInsurance.intValue() + " 无房：" +
                                    housingType.intValue() + " 无车：" + hasCar.intValue());
                        }
                    }
                }

                insert(kwXxjrFilter);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return sendFlag;
    }
}
